package handler

import (
	"github.com/kataras/iris"
	log "github.com/sirupsen/logrus"
	"src/db"
	"src/handler/tools"
	"src/modle"
	"sync"
)

type Executor struct {
}

func (Executor) executor(ctx iris.Context) {
	var req modle.RiskAssessmentReq
	if ctx.ReadJSON(&req) != nil || !tools.CheckUid(req.Uid) {
		internalServerError(ctx)
		return
	}
	//获取用户uid，和电话号码
	user, e := db.GetUsersInfo(req.Uid)
	if e != nil {
		log.Error(e.Error())
	}
	card, e := db.GetCardInfo(req.Uid)
	if e != nil {
		log.Error(e.Error())
	}
	log.Println("用户id:", user.Id)
	log.Println("用户信用卡id:", card.CardId)
	log.Println("用户phone:", user.Phone)
	// todo:多个黑名单库检测//失败时跳出
	re, eNo := BlackListCheck(card.CardId, user.Phone)
	//只有在被禁止的时候返回总状态需要调整为禁止
	//通过和异常直接跳过
	if eNo == Forbid {
		re.Conclusion.Result = modle.Failed
		ctx.JSON(re)
		log.Infof("用户 %d 黑名单检测未通过!",user.Id)
		return
	}

	// 当黑名单异常，返回re为空，未查到该用户，返回异常
	if re == nil {
		re = &modle.RiskAssessmentResp{}
		re.Conclusion.Result = modle.Exception
		ctx.JSON(re)
		log.Infof("用户 %d 黑名单检测异常!",user.Id)
		return
	}

	//创建对应的chan和存放相情的切片
	//oInfo最后就是响应中的detils
	//channel := new(chan modle.DetailsType)
	//oInfo := new([]modle.DetailsType)
	oInfo := make([]modle.DetailsType, 0)
	channel := make(chan modle.DetailsType)
	wg := &sync.WaitGroup{}

	// 启动风控检测
	e = Data{req.Uid, &channel, wg, &oInfo}.Run()
	if e != nil {
		//var resp modle.RiskAssessmentResp
		re.Conclusion.Result = modle.Exception
		ctx.JSON(re)
		return
	}

	//合计总分，返回结果
	re.Conclusion.Score = FullMark
	for _, v := range oInfo {
		re.Conclusion.Score += v.Score
		re.Details = append(re.Details, v)
	}
	re.Conclusion.Result, re.Conclusion.Reason = tools.PassCheck(re.Conclusion.Score)
	log.Printf("用户 %d 机审结果：%+v \n", req.Uid, re)
	ctx.JSON(re)
	return
}
